package com.learn.authorization.handler;

import com.alibaba.fastjson.JSON;
import com.learn.authorization.result.R;
import com.learn.authorization.utils.WebUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/04/16
 * @description 授权异常处理器,记得到配置类里面添加
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 可以获取HttpStatus枚举类的值
        R result = new R(HttpStatus.FORBIDDEN.value(), "权限不足");
        WebUtil.renderString(response, JSON.toJSONString(result));
    }
}
